require 'digest/sha1'

class User < ActiveRecord::Base
  has_one :lough
  has_many :articles
  has_many :password_recoveries
  has_one (:avatar,:class_name => 'Photo')
  
  # validations
  validates_presence_of :email, :login_name
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  validates_uniqueness_of :email, :login_name
  validates_length_of :login_name, :within => 3..30, :too_long => 'Please pick a shorter name', :too_short => 'Please pick a longer name'
  #validates_length_of :password, :within => 6..30, :too_long => 'Please pick a password less than 30 chars', :too_short => 'Please pick a password more than 6 chars'
  
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  
  def validate
    errors.add_to_base("Missing password") if encrypted_password.blank?
    
    if !password.blank?
      if password.length < 6
      	errors.add_to_base('Please pick a password more than 6 chars')
      end
      
      if password.length > 30
      	errors.add_to_base('Please pick a password less than 30 chars')
      end
    end
  end
  
  # authenticate user
  # if the login and pass are coupled, will return a user instance.
  def self.authenticate(login, pass)
    user = self.find( :first,
                      :conditions => ["login_name = ? OR email = ?", login, login])
    if user
      expected_password = encrypt_password(pass, user.salt)

      if user.encrypted_password != expected_password
        user = nil
      end
    end
    
    user
  end
  
  def self.authenticate?(login, pass)
    user = self.authenticate(login, pass)
    return false if user.nil?
    return true if user.login_name == login || user.email == login
    
    false
  end
  
  # password attributes
  
  def password=(newpass)
    @password = newpass
    return if newpass.blank?
    create_new_salt
    self.encrypted_password = User.encrypt_password(self.password, self.salt)
  end
  
  def password
    @password
  end
  
  # Add a new article
  def add_article(options)
    articles.build(options)
  end
  
  # Password Recovery 
  def add_pwd_recovery
    password_recoveries.build
  end
  
  protected
  
  def self.sha1(pass)
    Digest::SHA1.hexdigest(pass)
  end
  
  #before_create :crypt_password
  
  # Before saving the record to database we will crypt the password
  # using SHA1.
  # We never store the actual password in the DB.
  def self.encrypt_password(pass, salt)
    # puts ["password: ?", pass]
    # puts ["salt: ?", salt]
    string_to_hash = pass + "wibble" + salt
    sha1(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
  before_create :set_default_avatar
  
  def set_default_avatar
    write_attribute 'avatar', 'default.png'
  end
end
